'use strict';
var app = angular.module('app');
app.controller('rapidAuthController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster', '$modal',
    function($scope, $rootScope, $state, $timeout, toaster, $modal) {
        var title = '';
        var defaultAva = $rootScope.defaultAvatar;
        $scope.SubmitType = ''; //用于判断是否点击提交并完善信息按钮
        $scope.record = {};
        $scope.record.personType = '0'; // 0：租客   1：房东
        $scope.record.relationType = '0'; // 0：租赁   1：自有
        $scope.record.sex = '1'; // 1：男   2：女
        $scope.record.nation = '01';
        $scope.record.objectType = '1'; //楼栋ID
        $scope.record.appAvalible = '1'; //0：禁用   1：启用
        $scope.record.icCardUIDs = [];
        $scope.record.idCardUID = ''; //用于提交表单时判断是否为空（如未先定义，值为undefined,不满足判断要求）
        $scope.record.liveCardUID = '';
        $scope.cardStatus = "读卡";
        $scope.cardUUIDStatus = false; //身份证UID状态
        $scope.liveCardUUIDStatus = false; //居住证UID
        $scope.icCardUUIDStatus = false; //IC卡UID
        var timer1, timer2, timer3, prevCard;
        title = "快速授权";
        validate(null);

        setTimeout(function() {
            $scope.myCroppedImage = defaultAva;
            !$rootScope.$$phase && $scope.$apply();
        }, 300);
        $scope.title = $rootScope.title = title;
        $scope.loading = true;

        //判断浏览器是否为IE或edge
        BrowserType();

        function BrowserType() {
            if (!!window.ActiveXObject || "ActiveXObject" in window) {
                connect();
            }
        }

        //华视电子身份证读卡器连接
        function connect() {
            var CertCtl = document.getElementById("CertCtl");
            try {
                var result = CertCtl.connect();
                getStatus();
            } catch (e) {}
        }

        //华视电子身份证读卡器连接状态检测
        function getStatus() {
            var CertCtl = document.getElementById("CertCtl");
            try {
                var result = CertCtl.getStatus();
                var resultObj = eval('(' + result + ')'); //toJson操作
                console.log(typeof resultObj.status);
                resultObj.status ? $scope.cardStatus = "未连接" : $scope.cardStatus = "读卡";
            } catch (e) {}
        }
        //读卡器状态
        function clearCardStatus(status) {
            if (!!window.ActiveXObject || "ActiveXObject" in window) {} else {
                toaster.pop('error', '', '该功能只支持IE浏览器，请使用IE浏览器！');
                return;
            }
            var ports = webSerial.getComPorts(); //获取到端口号
            var coms = ports;
            if (!coms) {
                toaster.pop('error', '', "设备异常，请检查您的读卡设备！");
                return;
            }
            var baudRate = '115200';
            var result = webSerial.connect(coms, baudRate);
            if (result == "true" || result == true) {
                clearInterval(timer1)
                clearInterval(timer2)
                clearInterval(timer3)
                $scope.cardUUIDStatus = false;
                $scope.liveCardUUIDStatus = false;
                $scope.icCardUUIDStatus = false;
                $scope[status] = true;
            } else {
                toaster.pop('error', '', "设备异常，请检查您的读卡设备！");
            }
        }

        //获取卡号
        function cardHandle(data) {
            var code = data.split(" ");
            var targetStr = "";
            for (var i = 0; i < code.length; i++) {
                var tmp = parseInt(code[i], 16);
                targetStr += String.fromCharCode(tmp);
            }

            var cardId = targetStr.replace(/^0+/, "") //把设备读取卡号前面补的‘0’全部去掉
            cardId = cardId.replace(/(^\s*)|(\s*$)/g, ""); //把数据后面的回车空格去掉
            return cardId;
        }

        //华视电子身份证读卡器读卡
        $scope.readCert = function() {
            var CertCtl = document.getElementById("CertCtl");
            try {
                var result = CertCtl.readCert();
                var resultObj = eval('(' + result + ')'); //toJson操作

                if (resultObj.resultFlag == 0) {
                    //              resultObj.resultContent.certNumber = '220999199010177653'; //测试数据
                    $scope.checkIDCardNo(resultObj.resultContent); //将读取的卡号进行后台查询
                    //              $scope.record.IDCardNo = resultObj.resultContent.certNumber; //身份证号


                    //              $scope.record.personName = resultObj.resultContent.partyName;//身份证姓名
                    //              $scope.record.censusAddress = resultObj.resultContent.certAddress;//身份证户籍
                    //              
                    //              resultObj.resultContent.gender ? $scope.record.sex = 1 : $scope.record.sex = 2;//身份证性别'
                    //              $scope.record.nation = $("#nation option:contains('" + resultObj.resultContent.nation + "族')").attr('selected', true).val();//身份证民族
                    //              //身份证出生日期
                    //              var bornDay = resultObj.resultContent.bornDay.slice(0,4)+'-'+resultObj.resultContent.bornDay.slice(4,6)+'-'+resultObj.resultContent.bornDay.slice(6,8);
                    //              $("#birthday").val(bornDay);
                    //              //身份证头像
                    //              var imgBase64 = "data:image/jpeg;base64," + resultObj.resultContent.identityPic;
                    //              $("#headImag").prop('src',imgBase64);
                }

            } catch (e) {}
        }

        //表单的提交
        $scope.submit = function() {
            if (new Date($("#startDate").val()) > new Date($("#endDate").val())) {
                $("#endDate").focus();
                toaster.clear('*');
                toaster.pop('error', '', '开始时间不能大于结束时间');
                return;
            }
            if ($scope.record.icCardUIDs.length > 0 || $scope.record.idCardUID !== '' || $scope.record.liveCardUID !== '' || $scope.record.appAvalible == '1') {
                $scope.record.relationType = $scope.record.personType;
                $scope.record.birthday = $("#birthday").val();
                $scope.record.startDate = $("#startDate").val();
                $scope.record.endDate = $("#endDate").val();
                $scope.record.endTime = $("#endTime").val();
                var m = $scope.record;
                console.log(m);
                if ($scope.isuse == true) {
                    toaster.clear('*');
                    toaster.pop('error', '', '请修改手机号码');
                    return;
                }
                if (m) {
                    $scope.isDisabled = true; //提交disabled
                    $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        contentType: 'application/json;charset=UTF-8',
                        url: 'dac/authm/quick/auth',
                        data: angular.toJson($scope.record)
                    }).then(function(result) {
                        if (result.httpCode == 200) { //成功
                            toaster.clear('*');
                            toaster.pop('success', '', "保存成功");
                            if ($scope.SubmitType == 'addDetail') {
                                $scope.openDetailInfo(result.data.personId, $scope.record.mobileNo);
                            } else {
                                $timeout(function() {
                                    $state.go('main.authm.cardAuth.list');
                                }, 2000);
                            }
                        } else {
                            toaster.clear('*');
                            toaster.pop('error', '', result.msg);
                            $scope.isDisabled = false;
                        }
                    });
                }

            } else {
                alert('身份证、居住证、IC卡、APP开门四者至少填一项');
                return //如果三者都不填的话就不执行下面的代码，不提交！
            }

        }

        // 手机号码验证    
        jQuery.validator.addMethod("isMobile", function(value, element) {
            var length = value.length;
            return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/.test(value));
        }, "请填写正确的手机号码");

        // 身份证号码验证
        jQuery.validator.addMethod("isIdCardNo", function(value, element) {
            //var idCard = /^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\w)$/;   
            return this.optional(element) || isIdCardNo(value);
        }, "请填写正确的身份证号");

        //身份证号码的验证规则
        function isIdCardNo(num) {
            var len = num.length;
            var re;
            if (len == 15)
                re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{2})(\w)$/);
            else if (len == 18)
                re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\w)$/);
            else {
                //alert("输入的数字位数不对。"); 
                return false;
            }
            var a = num.match(re);
            if (a != null) {
                if (len == 15) {
                    var D = new Date("19" + a[3] + "/" + a[4] + "/" + a[5]);
                    var B = D.getYear() == a[3] && (D.getMonth() + 1) == a[4] && D.getDate() == a[5];
                } else {
                    var D = new Date(a[3] + "/" + a[4] + "/" + a[5]);
                    var B = D.getFullYear() == a[3] && (D.getMonth() + 1) == a[4] && D.getDate() == a[5];
                }
                if (!B) {
                    //alert("输入的身份证号 "+ a[0] +" 里出生日期不对。"); 
                    return false;
                }
            }
            if (!re.test(num)) {
                //alert("身份证最后一位只能是数字和字母。");
                return false;
            }
            return true;
        }

        //表单验证
        function validate(userId) {
            jQuery('form').validate({
                rules: {
                    IDCardNo: {
                        required: true,
                        isIdCardNo: true
                    },
                    personName: {
                        required: true
                    },
                    censusAddress: {
                        required: true
                    },
                    birthday: {
                        required: true
                    },
                    mobileNo: {
                        required: true,
                        isMobile: true
                    },
                    startDate: {
                        required: true
                    },
                    endDate: {
                        required: true
                    },
                    buildingAddress: {
                        required: true
                    },
                    endTime: {
                        required: true
                    }
                },
                messages: {
                    IDCardNo: {
                        required: '请填写身份证号'
                    },
                    personName: {
                        required: '请填写人员姓名'
                    },
                    censusAddress: {
                        required: '请填写户籍地址'
                    },
                    birthday: {
                        required: '请选择出生日期'
                    },
                    mobileNo: {
                        required: '请填写手机号码'
                    },
                    startDate: {
                        required: '请选择开始居住时间'
                    },
                    endDate: {
                        required: '请选择结束居住时间'
                    },
                    buildingAddress: {
                        required: '请填写楼栋地址'
                    },
                    endTime: {
                        required: '请选择结束授权时间'
                    }
                },
                submitHandler: function() {
                    $scope.submit();
                }
            });
        }
        //生日选项
        $scope.birthOptions = {
            startingDay: 1,
            class: 'datepicker',
            maxDate: new Date().getTime()
        };
        //居住时间选项
        $scope.liveOptions = {
            startingDay: 1,
            class: 'datepicker',
            minDate: new Date().getTime()
        };
        //授权时间选项
        $scope.authOptions = {
            startingDay: 1,
            class: 'datepicker',
            minDate: new Date().getTime()
        };
        //日期控件
        $scope.format = "yyyy-MM-dd";
        $scope.openDatepicker = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            switch (i) {
                case 1:
                    $scope.birthday = true;
                    break;
                case 2:
                    $scope.startDate = true;
                    break;
                case 3:
                    $scope.endDate = true;
                    break;
                case 4:
                    $scope.endTime = true;
                    break;
                case 5:
                    $scope.detailLiveTime = true;
                    break;
                default:
                    return;
            }
        }

        //  //开始和结束时间判断
        //  $scope.dateJudge = function(type) {
        //      if(($scope.record.startDate).getTime()>($scope.record.endDate).getTime()){
        //          if(type == 'startDate'){
        //              $scope.record.startDate = $("#endDate").val();
        //              toaster.clear('*');
        //              toaster.pop('error', '', '开始时间不能大于结束时间');
        //          }else{
        //              $scope.record.endDate = $("#startDate").val();
        //              toaster.clear('*');
        //              toaster.pop('error', '', '结束时间不能小于开始时间');
        //          }
        //      }
        //  }

        //根据人员类型选择显示不同的楼栋地址（租客显示房屋列表，房东选择楼栋列表）
        $scope.openInfo = function() {
            var personType = $scope.record.personType;
            if ("0" == personType) {
                $scope.openHouseInfo();
            } else if ("1" == personType) {
                $scope.openNowAddress($scope.record.personId);
            }
        }

        //选择房屋类型时清空房屋地址，重新选择
        $scope.rewriteInfo = function() {
            $scope.buildingAddress = "";
        };

        //楼栋模态框
        $scope.openNowAddress = function(items) {
            $scope.items = items;
            var modalInstance = $modal.open({
                templateUrl: 'NowAddress.html', //script标签中定义的id
                controller: 'NowAddressModalCtrl', //modal对应的Controller
                size: 'lg',
                resolve: {
                    items: function() {
                        return $scope.items;
                    }
                }
            });

            modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

            });
            modalInstance.result.then(function(result) {
                console.log(result)
                $scope.record.deviceId = result.deviceId;
                $scope.buildingAddress = result.buildingAddress;
                $scope.record.objectId = result.buildingId
            }, function(reason) {
                console.log(reason);
            });

        };

        //房屋模态框
        $scope.openHouseInfo = function() {
            var modalInstance = $modal.open({
                templateUrl: 'personHouseList.html', // script标签中定义的id
                controller: 'personHouseModalCtrl', // modal对应的Controller
                size: 'lg',
                resolve: {
                    relationType: function() { // 向模态框app中传递参数
                        return $scope.record.relationType;
                    }
                }
            });
            modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

            });
            modalInstance.result.then(function(result) {
                $scope.record.deviceId = result[1];
                $scope.buildingAddress = result[2];
                $scope.record.objectId = result[3];
            }, function(reason) {
                console.log(reason);
            });
        };

        //姓名模态框
        $scope.openPerson = function(buildingId) {
            console.log(buildingId);
            $scope.items = buildingId;
            var modalInstance = $modal.open({
                templateUrl: 'personList.html', //script标签中定义的id
                controller: 'personModalCtrl', //modal对应的Controller
                size: 'lg',
                resolve: {
                    items: function() {
                        return $scope.items;
                    }
                }
            });

            modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

            });
            modalInstance.result.then(function(result) {
                $scope.personName = result[0];
                $scope.record.personName = result[0];
                //          $scope.record['personId'] = result[1];
                //          $scope.record.authNo = result[2];
            }, function(reason) {
                console.log(reason);
            });

        };

        //详细信息模态框
        $scope.openDetailInfo = function(personId, mobileNo) {
            $scope.items = {};
            $scope.items.personId = personId;
            $scope.items.mobileNo = mobileNo;
            var modalInstance = $modal.open({
                templateUrl: 'detailInfo.html', //script标签中定义的id
                controller: 'DetailInfoModalCtrl', //modal对应的Controller
                size: 'lg',
                resolve: {
                    items: function() {
                        return $scope.items;
                    }
                }
            });

            modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

            });
            modalInstance.result.then(function(result) {

            }, function(reason) {
                $state.go('main.authm.cardAuth.list');
                console.log(reason);
            });
        };

        //读取身份证号
        $scope.readCard = function() {
            //var str;
            //SynIDCard1.Port = 1001;//document.all['Port'].value
            //console.log("端口设置为"+SynIDCard1.Port);
            //var str=SynIDCard1.Init();
            //console.log("初始化结果"+str);
            //console.log(SynIDCard1.ReadCard());
            //$scope.record.personName = SynIDCard1.NameL;
            //$scope.record.sex = SynIDCard1.Sex;
            //$scope.record.nation = SynIDCard1.NationL;
            //$scope.record.birthday = new Date(SynIDCard1.BornL);//SynIDCard1.BornL;
            //$scope.record.censusAddress = SynIDCard1.Address;
            //$scope.record.IDCardNo = SynIDCard1.CardNo;

            document.getElementById("IdCardRead").connectDevice();
            //
            IdCardRead.readCard();
            //console.log("读卡成功"                           );
            //console.log("姓名:"+IdCardRead.NameA           );
            //console.log("性别:"+IdCardRead.Sex             );
            //console.log("民族:"+IdCardRead.Nation +""+IdCardRead.NationL         );
            //console.log("出生日期:"+IdCardRead.Born        );
            //console.log("地址:"+IdCardRead.Address         );
            //console.log("身份证号:"+IdCardRead.CardNo      );
            //console.log("有效期开始:"+IdCardRead.UserLifeB );
            //console.log("有效期结束:"+IdCardRead.UserLifeE );
            //console.log("发证机关:"+IdCardRead.Police      );
            //console.log("照片文件名:"+IdCardRead.PhotoName );
            //console.log("照片文件名:"+IdCardRead.base64str );
            //$("#headImag").attr("src","data:image/png;base64,"+IdCardRead.base64str)

            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                url: 'dac/userManager/headupload',
                data: angular.toJson({ 'headPic': IdCardRead.base64str })
            }).then(function(result) {
                $scope.loading = false;
                if (result.httpCode == 200) {
                    //$scope.record.authcode = result.hex;
                    $("#headImag").attr("src", result.path)
                    var photopath = "/dac/userManager/headdownload?fileId=" + result.path;
                    $scope.record.photoURL = photopath;
                    $("#headImag").attr("src", photopath);
                } else {
                    //$scope.msg = result.msg;
                    toaster.clear('*');
                    toaster.pop('error', '', "照片上传失败！");
                }
                $scope.$apply();
            });

            var birthYear = IdCardRead.Born.substring(0, 4);
            var birthMonth = IdCardRead.Born.substring(4, 6);
            var birthDay = IdCardRead.Born.substring(6, 8);


            $scope.record.personName = IdCardRead.NameA.replace(/(^\s*)|(\s*$)/g, "");
            $scope.record.sex = IdCardRead.Sex;
            $scope.record.nation = IdCardRead.Nation;
            $scope.record.birthday = birthYear + "-" + birthMonth + "-" + birthDay; //SynIDCard1.BornL;
            //console.log(birthYear+"-"+birthMonth+"-"+birthDay);
            $scope.record.censusAddress = IdCardRead.Address.replace(/(^\s*)|(\s*$)/g, "");
            $scope.record.IDCardNo = IdCardRead.CardNo;
        };

        //读取身份证UID
        $scope.readIdCard = function() {
            // var ports = webSerial.getComPorts();
            // var coms = ports;
            // var baudRate = '115200';
            // clearCardStatus(coms, 'cardUUIDStatus');
            // var result = webSerial.connect(coms, baudRate);
            clearCardStatus('cardUUIDStatus');
            var webSerial1 = document.getElementById("webSerial");
            // $scope.cardUUIDStatus = true;
            var s = 0;
            timer1 = setInterval(function() {
                s += 2;
                var data1 = webSerial1.Receive();
                if (data1 != null) {
                    var card_id = cardHandle(data1);
                    if ($scope.record.liveCardUID.indexOf(card_id) == -1 && $scope.record.icCardUIDs.toString().indexOf(card_id) == -1) {
                        $scope.cardUUIDStatus = false;
                        $scope.record.idCardUID = card_id;
                        prevCard = card_id;
                        webSerial.close();
                        clearInterval(timer1);
                        $scope.$apply();
                    }
                }
                if (s >= 10) {
                    s = 0;
                    $scope.cardUUIDStatus = false;
                    $scope.$digest()
                    clearInterval(timer1);
                    toaster.pop('error', '', "读取超时或请确认是否重复读卡！");
                }

            }, 2000);
        }

        //读取居住证UID
        $scope.readLiveCard = function() {
            // var ports = webSerial.getComPorts();
            // var coms = ports;
            // var baudRate = '115200';
            // clearCardStatus(coms, 'liveCardUUIDStatus');
            // var result = webSerial.connect(coms, baudRate);
            clearCardStatus('liveCardUUIDStatus');
            var webSerial1 = document.getElementById("webSerial");
            var s = 0;
            timer2 = setInterval(function() {
                s += 2;
                var data1 = webSerial1.Receive();
                if (data1 != null) {
                    var card_id = cardHandle(data1);
                    if ($scope.record.idCardUID.indexOf(card_id) == -1 && $scope.record.icCardUIDs.toString().indexOf(card_id) == -1) {
                        $scope.liveCardUUIDStatus = false;
                        $scope.record.liveCardUID = card_id;
                        prevCard = card_id;
                        webSerial.close();
                        clearInterval(timer2);
                        $scope.$apply();
                    }
                }
                if (s >= 10) {
                    s = 0;
                    $scope.liveCardUUIDStatus = false;
                    $scope.$digest();
                    clearInterval(timer2);
                    toaster.pop('error', '', "读取超时或请确认是否重复读卡！");
                }

            }, 2000);
        }

        //读取IC卡UID
        $scope.readIcCard = function() {
            // var ports = webSerial.getComPorts(); //获取到端口号
            // var coms = ports;
            // var baudRate = '115200';
            // // clearCardStatus(coms, 'icCardUUIDStatus');
            // var result = webSerial.connect(coms, baudRate);
            clearCardStatus('icCardUUIDStatus');
            var webSerial1 = document.getElementById("webSerial"); //页面上的特定结构
            var s = 0;
            timer3 = setInterval(function() { //设置定时器，检测刷卡动作
                s += 2;
                var data1 = webSerial1.Receive();
                if (data1) { //刷卡有数据时，对数据处理，关闭定时器与控件
                    var card_id = cardHandle(data1);
                    if ($scope.record.liveCardUID.indexOf(card_id) == -1 && $scope.record.idCardUID.indexOf(card_id) == -1) {
                        $scope.icCardUUIDStatus = false;
                        $scope.record.icCardUIDs.push(card_id);
                        prevCard = card_id;
                        webSerial.close();
                        clearInterval(timer3);
                        $scope.$apply();
                    }

                }
                if (s >= 10) {
                    s = 0;
                    $scope.icCardUUIDStatus = false;
                    $scope.$digest();
                    clearInterval(timer3);
                    toaster.pop('error', '', "读取超时或请确认是否重复读卡！");
                }


            }, 2000);

        }

        //删除已录入的卡号
        $scope.del = function(idx) {
            $scope.record.icCardUIDs.splice(idx, 1);
            console.log($scope.record.icCardUIDs);
        };

        //手机号码唯一校验
        $scope.checkPhoneNumber = function() {
            $scope.number = $('#mobileNo').val();
            var phoneTest = /^1[3456789]\d{9}$/;
            if ($scope.number && phoneTest.test($scope.number)) {
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    url: '/dac/userManager/checkMobile',
                    data: angular.toJson({ 'mobileNo': $scope.number })
                }).then(function(result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                        $scope.isuse = false;
                    } else if (result.httpCode == 666) {
                        $scope.isuse = true;
                    } else {
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }

        }

        //判断身份证及授权
        $scope.checkIDCardNo = function(data) {
            $scope.isDisabled = false; //允许提交
            $scope.IDCardNo = $('#IDCardNo').val() || data.certNumber;
            if ($scope.IDCardNo.length == 15 || $scope.IDCardNo.length == 18) {
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    url: '/dac/authm/quick/checkidcard',
                    data: angular.toJson({ 'IDCardNo': $scope.IDCardNo })
                }).then(function(result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) { //身份证在数据库中存在
                        var item = result.data;
                        $scope.inputDisable = true;
                        $scope.record.IDCardNo = item.IDCardNo;
                        $scope.record.personName = item.personName;
                        $scope.record.birthday = item.birthday;
                        $scope.record.nation = item.nation;
                        $scope.record.sex = item.sex;
                        $scope.record.mobileNo = item.mobileNo;
                        $scope.record.personType = item.personType;
                        $scope.record.personId = item.personId;
                        $scope.record.censusAddress = item.censusAddress;
                    } else if (result.httpCode == 500) { //身份证在数据库中不存在或者已授权
                        if (result.msg == '身份证已存在，并且已关联授权！') {
                            // toaster.clear('*');
                            // toaster.pop('error', '', '用户已经授权，可在授权管理中维护');
                            // $scope.isDisabled = true; //禁止提交
                        } else {
                            if (data) {
                                $scope.record.IDCardNo = data.certNumber; //身份证号
                                $scope.record.personName = data.partyName; //身份证姓名
                                $scope.record.censusAddress = data.certAddress; //身份证户籍

                                data.gender ? $scope.record.sex = 1 : $scope.record.sex = 2; //身份证性别'
                                $scope.record.nation = $("#nation option:contains('" + data.nation + "族')").attr('selected', true).val(); //身份证民族
                                //身份证出生日期
                                var bornDay = data.bornDay.slice(0, 4) + '-' + data.bornDay.slice(4, 6) + '-' + data.bornDay.slice(6, 8);
                                $("#birthday").val(bornDay);
                                //身份证头像
                                var imgBase64 = "data:image/jpeg;base64," + data.identityPic;
                                $("#headImag").prop('src', imgBase64);
                            } else {
                                $scope.inputDisable = false;
                                //                      $scope.record.personName = '';
                                //                      $scope.record.birthday = '';
                                //                      $scope.record.nation = '01';
                                //                      $scope.record.sex = '1';
                                //                      $scope.record.mobileNo = '';
                                //                      $scope.record.personType = '0';
                                //                      $scope.record.censusAddress = '';
                                delete $scope.record.personId;
                            }
                        }
                    } else {
                        $scope.inputDisable = false;
                        $scope.msg = result.msg;
                    }
                    $scope.$apply();
                });
            }
        }

        //选取时间
        $scope.chooceTime = function(Months) {
            console.log(Months);
            var endTime = '';
            if (Months && Months != undefined) {
                var date = new Date();
                date.setMonth(date.getMonth() + Months);
                var year = date.getFullYear();
                var Month = date.getMonth() + 1;
                var day = date.getDate();
                if (Month > 12) {
                    year = year + 1;
                    Month = Month - 12;
                }
                switch (Month) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        console.log(Month)
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        if (day > 30) {
                            day = 30;
                        }
                        break;
                    case 2:
                        if (day > 28) {
                            day = 29;
                        }
                        break;
                    default:
                        console.log(Month);
                }
                if (Month < 10) {
                    Month = '0' + Month
                }
                if (day < 10) {
                    day = '0' + day
                }
                endTime = year + '-' + Month + '-' + day;
                console.log(endTime);
                $scope.record.endTime = endTime;
            } else {
                $scope.record.endTime = '2099-12-31';
            }
        };

        //判断点击保存还是提交并完善信息操作
        $scope.setSubmitType = function() {
            $scope.SubmitType = 'addDetail';
        }
    }
]);

//房屋模态框
app.controller('personHouseModalCtrl', function($scope, $rootScope, $modal,
    $modalInstance, relationType) {

    // 查询条件、参数，用于传递给后台使用
    $scope.param = {};

    // 若为1则显示房东复选框的模态框；若为0则显示租客单选框的模态框。
    $scope.tag = 0;

    $scope.search = function() {
        $scope.loading = true;
        if ($scope.pageFlag != 1) { //未点击翻页
            $scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
        } else { //点击翻页
            $scope.pageFlag = 2; //将开关值设置为2
        }
        $scope.param.houseStatus = "4";
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dac/bm//house/deviceList',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                $scope.pageInfo = result;
                console.log(result);
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }
    // 调用查询函数
    $scope.search();

    $scope.selectHouses = function(deviceId, address, houseId) {
        $scope.params = [];
        //          $scope.params[0] = "flagController"; //用于区分租客和房东，有flagController则代表着租客，没有则是房东。
        $scope.params[1] = deviceId;
        $scope.params[2] = address;
        $scope.params[3] = houseId;
        // 这里需要将复选框选中的属性取到，然后交给$modalInstance回显到修改页面
        // 修改页面将复选框传来的值再传给后台
        $modalInstance.close($scope.params);
    };

    // 取消
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    // 翻页
    $scope.pagination = function(page) {
        $scope.param.pageNum = page;
        $scope.pageFlag = 1; //将开关值设置为1
        $scope.search();
    };

    // 定义一个数组，用于接收房东复选框的多值
    $scope.selected = [];
    $scope.houseIdArray = [];
    $scope.houseAddress = [];

    $scope.isChecked = function(houseId) {
        return $scope.selected.indexOf(houseId) >= 0;
    };

    $scope.updateSelection = function($event, item) {
        var checkbox = $event.target;
        var checked = checkbox.checked;
        if (checked) {
            $scope.selected.push(item.houseName + "(" + item.houseCode + ")");
            $scope.houseIdArray.push(item.houseId);
            $scope.houseAddress.push(item.address);
        } else {
            var idx = $scope.selected.indexOf(item.houseName + "(" + item.houseCode + ")");
            $scope.selected.splice(idx, 1);

            var houseIdx = $scope.houseIdArray.indexOf(item.houseId);
            $scope.houseIdArray.splice(houseIdx, 1);

            var addressIdx = $scope.houseAddress.indexOf(item.address);
            $scope.houseAddress.splice(addressIdx, 1);
        }
    };

    $scope.saveHouse = function() {
        $scope.records = {};
        $scope.records.selected = $scope.selected;
        $scope.records.houseIdArray = $scope.houseIdArray;
        $scope.records.houseAddress = $scope.houseAddress;
        $modalInstance.close($scope.records);
    } // 定义一个数组，用于接收房东复选框的多值
    $scope.selected = [];
    $scope.houseIdArray = [];
    $scope.houseAddress = [];

    $scope.isChecked = function(houseId) {
        return $scope.selected.indexOf(houseId) >= 0;
    };

    $scope.updateSelection = function($event, item) {
        var checkbox = $event.target;
        var checked = checkbox.checked;
        if (checked) {
            $scope.selected.push(item.houseName + "(" + item.houseCode + ")");
            $scope.houseIdArray.push(item.houseId);
            $scope.houseAddress.push(item.address);
        } else {
            var idx = $scope.selected.indexOf(item.houseName + "(" + item.houseCode + ")");
            $scope.selected.splice(idx, 1);

            var houseIdx = $scope.houseIdArray.indexOf(item.houseId);
            $scope.houseIdArray.splice(houseIdx, 1);

            var addressIdx = $scope.houseAddress.indexOf(item.address);
            $scope.houseAddress.splice(addressIdx, 1);
        }
    };

    $scope.saveHouse = function() {
        $scope.records = {};
        $scope.records.selected = $scope.selected;
        $scope.records.houseIdArray = $scope.houseIdArray;
        $scope.records.houseAddress = $scope.houseAddress;
        $modalInstance.close($scope.records);
    } // 定义一个数组，用于接收房东复选框的多值
    $scope.selected = [];
    $scope.houseIdArray = [];
    $scope.houseAddress = [];

    $scope.isChecked = function(houseId) {
        return $scope.selected.indexOf(houseId) >= 0;
    };

    $scope.updateSelection = function($event, item) {
        var checkbox = $event.target;
        var checked = checkbox.checked;
        if (checked) {
            $scope.selected.push(item.houseName + "(" + item.houseCode + ")");
            $scope.houseIdArray.push(item.houseId);
            $scope.houseAddress.push(item.address);
        } else {
            var idx = $scope.selected.indexOf(item.houseName + "(" + item.houseCode + ")");
            $scope.selected.splice(idx, 1);

            var houseIdx = $scope.houseIdArray.indexOf(item.houseId);
            $scope.houseIdArray.splice(houseIdx, 1);

            var addressIdx = $scope.houseAddress.indexOf(item.address);
            $scope.houseAddress.splice(addressIdx, 1);
        }
    };

    $scope.saveHouse = function() {
        $scope.records = {};
        $scope.records.selected = $scope.selected;
        $scope.records.houseIdArray = $scope.houseIdArray;
        $scope.records.houseAddress = $scope.houseAddress;
        $modalInstance.close($scope.records);
    }
});

//现住地址模态框控制器
app.controller('NowAddressModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {
    if (items) {
        $scope.url = '/dac/authm/build/bypersonlist'
    } else {
        $scope.url = '/dac/authm/build/list'
    }
    $scope.param = {};
    $scope.search = function() {
        $scope.loading = true;
        if ($scope.pageFlag != 1) { //未点击翻页
            $scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
        } else { //点击翻页
            $scope.pageFlag = 2; //将开关值设置为2
        }
        $scope.param.cityId = $('#city').find("option:selected").data('code'); //获取value的值
        $scope.param.areaId = $('#area').find("option:selected").data('code'); //获取value的值
        $scope.param.streetId = $('#street').find("option:selected").data('code'); //获取value的值
        $scope.param.roadId = $('#road').find("option:selected").data('code'); //获取value的值
        $scope.param.communityId = $('#quarters').find("option:selected").data('code'); //获取value的值
        $scope.param.buildingNo = $('#buildingNo').val();
        $scope.param.deviceCode = $('#deviceCode').val();
        $scope.param.deviceName = $('#deviceName').val();
        $scope.param.personId = $('#personId').val();
        $scope.param.buildName = $('#buildName').val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: $scope.url,
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                console.log(result)
                $scope.pageInfo = result;
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }
    $scope.search();

    //7级地址下拉数据
    //市
    $scope.getaddress = function() {
        $scope.param = {
            parentCode: 440000 //广东省
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.city = result.data;
            console.log(result);
        })
    }
    $scope.getaddress();
    //区
    $scope.getarea = function() {
        var parentCode = $('#city').find("option:selected").data('code'); //获取value的值
        console.log(parentCode);
        $scope.param = {
            parentCode: parentCode //广州市区级
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.area = result.data;
            console.log(result);
        })
    }
    //乡镇/街道
    $scope.getStree = function() {
        var parentCode = $('#area').find("option:selected").data('code'); //获取value的值
        console.log(parentCode);
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.stree = result.data;
            console.log(result);
        })
    }
    //路
    $scope.getRoad = function() {
        var parentCode = $('#street').find("option:selected").data('code'); //获取value的值;
        console.log(parentCode)
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.roud = result.data;
            console.log(result);
        })
    }
    //小区
    $scope.getQuarters = function() {
        var parentCode = $('#road').find("option:selected").data('code'); //获取value的值;
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.quarters = result.data;
            console.log(result);
        })
    }
    //房号
    $scope.getHouseNo = function() {
        var parentCode = $('#quarters').find("option:selected").data('code'); //获取value的值;
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.houseNo = result.data;
            console.log(result);
        })
    }
    //选择按钮操作
    $scope.selectBuilding = function(buildingId, buildingAddress, deviceId) {
        $scope.buildingId = {
            buildingId: buildingId,
            buildingAddress: buildingAddress,
            deviceId: deviceId
        }
        $modalInstance.close($scope.buildingId);
    };
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
    // 翻页
    $scope.pagination = function(page) {
        $scope.param.pageNum = page;
        $scope.pageFlag = 1; //将开关值设置为1
        $scope.search();
    };

});

//姓名模态框控制器
app.controller('personModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {

    $scope.paramP = {
        buildingId: items //buildingId
    };

    $scope.searchP = function() {
        $scope.loading = true;
        if ($scope.pageFlag != 1) { //未点击翻页
            $scope.paramP.pageNum = 1; //将页码设置为1，即跳转回第一页
        } else { //点击翻页
            $scope.pageFlag = 2; //将开关值设置为2
        }
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dac/authm/person/list',
            data: angular.toJson($scope.paramP)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                console.log(result.data)
                $scope.pageInfo = result;
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }

    $scope.searchP();

    $scope.selectPerson = function(pid, personName, IDCardNo) {
        $scope.params = [];
        $scope.params[0] = personName;
        $scope.params[1] = pid;
        $scope.params[2] = IDCardNo;
        $modalInstance.close($scope.params);
    };
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    // 翻页
    $scope.pagination = function(page) {
        $scope.paramP.pageNum = page;
        $scope.pageFlag = 1; //将开关值设置为1
        $scope.searchP();
    };
});

//个人信息模态框控制器
app.controller('DetailInfoModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items, toaster) {
    $scope.detailParams = {};
    $scope.detailParams.personId = items.personId;
    $scope.detailParams.mobileNo = items.mobileNo;
    $scope.detailParams.marriageState = '10';
    $scope.detailParams.isWriteOff = '1';
    $scope.detailParams.personState = '1';
    $scope.detailParams.contraceptionState = '1';
    $scope.rNationality = false;
    $scope.rDetailLiveTime = false;
    $scope.rPoliceAreaId = false;
    //      $scope.bDisabled = false;

    $scope.checkStatus = function(name) {
        switch (name) {
            case 'nationality':
                if ($scope.detailParams.nationality) {
                    $scope.rNationality = false;
                } else {
                    $scope.rNationality = true;
                }
                break;
            case 'detailLiveTime':
                if ($scope.detailParams.detailLiveTime) {
                    $scope.rDetailLiveTime = false;
                } else {
                    $scope.rDetailLiveTime = true;
                }
                break;
            case 'policeAreaId':
                if ($scope.detailParams.policeAreaId) {
                    $scope.rPoliceAreaId = false;
                } else {
                    $scope.rPoliceAreaId = true;
                }
                break;
            default:
                console.log('');
        }
    }

    $scope.sendDetailInfo = function() {
        $scope.detailParams.detailLiveTime = $("#detailLiveTime").val();
        if ($scope.detailParams.nationality) {
            $scope.rNationality = false;
        } else {
            $scope.rNationality = true;
            $("#nationality").focus();
        }
        if ($scope.detailParams.detailLiveTime) {
            $scope.rDetailLiveTime = false;
        } else {
            $scope.rDetailLiveTime = true;
            $("#detailLiveTime").focus();
        }
        if ($scope.detailParams.policeAreaId) {
            $scope.rPoliceAreaId = false;
        } else {
            $scope.rPoliceAreaId = true;
            $("#policeAreaId").focus();
        }
        if ($scope.rNationality || $scope.rDetailLiveTime || $scope.rPoliceAreaId) {
            return;
        } else {
            $scope.detailParams.status = '0';
        }
        $scope.detailParams.id = $scope.detailParams.personId;
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dac/userManager/saveOrUpdate',
            data: angular.toJson($scope.detailParams)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                toaster.clear('*');
                toaster.pop('success', '', "保存成功");
                $scope.cancel();
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    //日期控件
    $scope.dateOptions = {
        startingDay: 1,
        class: 'datepicker',
        minDate: new Date().getTime()
    };
    $scope.format = "yyyy-MM-dd";
    $scope.openDatepicker = function($event, i) {
        $event.preventDefault();
        $event.stopPropagation();
        switch (i) {
            case 1:
                $scope.birthday = true;
                break;
            case 2:
                $scope.startDate = true;
                break;
            case 3:
                $scope.endDate = true;
                break;
            case 4:
                $scope.endTime = true;
                break;
            case 5:
                $scope.detailLiveTime = true;
                break;
            default:
                return;
        }
    }

    //警务区的模态框
    $scope.openjwqdm = function() {
        var modalInstance = $modal.open({
            templateUrl: 'jwq.html', // script标签中定义的id
            controller: 'jwqModalCtrl', // modal对应的Controller
            size: 'lg'
            // resolve : {
            //     personType : function() {// 向模态框app中传递参数
            //        return $scope.record.personType;
            //     }
            // }
        });
        //选择之后回显到页面上来
        modalInstance.result.then(function(result) { //这里的result是下面的模态回调函数的值
            $scope.detailParams.policeAreaId = result[1];
            $scope.detailParams.policeAreaName = result[2];
        }, function(reason) {
            console.log(reason);
        });
    };
});

//警务区代码模态框控制器
app.controller('jwqModalCtrl', function($scope, $rootScope, $modal, $modalInstance) {

    // 查询条件、参数，用于传递给后台使用
    $scope.param = {};
    // 若为1则显示房东复选框的模态框；若为0则显示租客单选框的模态框。
    $scope.tag = 0;

    $scope.search = function() {
        $scope.loading = true;
        if ($scope.pageFlag != 1) { //未点击翻页
            $scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
        } else { //点击翻页
            $scope.pageFlag = 2; //将开关值设置为2
        }
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: 'dac/userManager/jwqdm/list',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                $scope.pageInfo = result;
                //console.log(result);
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }

    // 调用查询函数
    $scope.search();

    $scope.selectjwq = function(jwqdm, jwqmc) {
        $scope.params = [];
        $scope.params[1] = jwqdm;
        $scope.params[2] = jwqmc;
        // 这里需要将复选框选中的属性取到，然后交给$modalInstance回显到修改页面
        // 修改页面将复选框传来的值再传给后台
        $modalInstance.close($scope.params);
    };

    // 取消
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    // 翻页
    $scope.pagination = function(page) {
        $scope.param.pageNum = page;
        $scope.pageFlag = 1; //将开关值设置为1
        $scope.search();
    };


});